/**
 * 
 */
package com.winit.openapi.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ShipperAddressService;
import com.winit.erp.spi.bpartner.command.ShipperAddressCommand;
import com.winit.erp.spi.bpartner.command.ShipperAddressDeleteCommand;
import com.winit.erp.spi.bpartner.command.ShipperAddressQueryCommand;
import com.winit.erp.spi.bpartner.command.ShipperAddressUpdateCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.bpartner.vo.ShipperAddress;
import com.winit.erp.spi.user.vo.User;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 寄件人地址维护
 * 
 * @author kang.wang 2015-1-5 下午8:45:46
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/shipperAddr")
public class ShipperAddrController extends BaseController {

    @Resource
    private ShipperAddressService shipperAddressService;

    /**
     * @param shipperAddressService the shipperAddressService to set
     */
    public void setShipperAddressService(ShipperAddressService shipperAddressService) {
        this.shipperAddressService = shipperAddressService;
    }

    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        ShipperAddressCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validCreateShipperAddress(json);
            command = buildShipperAddressCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口创建寄件人地址
        Long shipperAddrId = shipperAddressService.insertShipperAddressById(command);

        // 返回寄件人地址ID
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("shipperAddrId", shipperAddrId);
        responseMsg.setData(data);

        return SUCCESS;
    }

    @RequestMapping(value = "/update")
    public String update(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        ShipperAddressUpdateCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validUpdateShipperAddress(json);
            command = buildUpdateShipperAddressCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口创建寄件人地址
        boolean result = shipperAddressService.updateShipperAddressById(command);

        // 返回寄件人地址ID
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("result", result);

        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/delete")
    public String delete(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        ShipperAddressDeleteCommand commandDelete = null;
        ShipperAddressQueryCommand commandQuery = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validShipperAddressId(json);
            commandDelete = buildDeleteShipperAddressCommand(json);
            commandQuery = buildQueryShipperAddressCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 调用接口查询寄件人地址
        ShipperAddress shipperAddress = shipperAddressService.queryShipperAddressById(commandQuery);

        if (shipperAddress == null) {
            throw new ApiException(ErrorCode.FIELD_ENDER_ID_NOT_EXIST);
        }
        // 调用接口删除寄件人地址
        boolean result = shipperAddressService.deleteShipperAddressById(commandDelete);

        // 返回寄件人地址ID
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("result", result);

        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Searchable searchable = Searchable.newSearchable();
        searchable.setPage(ApiConstant.PAGE_NO_DEFAULT - 1, ApiConstant.PAGE_SIZE_DEFAULT);
        searchable.addSort(new Sort(Direction.DESC, "updated"));

        User user = (User) CommandContext.getContext().get(ApiConstant.API_USER);

        searchable.and(SearchFilterHelper.newCondition("C_BPARTNER_ID", SearchOperator.eq, user.getBpartnerId()));

        // 调用接口创建寄件人地址
        Page<ShipperAddress> pagelist = shipperAddressService.queryPageShipperAddress(searchable);

        if (pagelist != null) {
            List<Map<String, Object>> list = buildReturnShipperAddressList(pagelist.getContent());
            responseMsg.setData(list);
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();

        ShipperAddressQueryCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validShipperAddressId(json);
            command = buildQueryShipperAddressCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Bpartner partner = (Bpartner) CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        command.setbPartnerId(partner.getcBpartnerId());
        // 调用接口创建寄件人地址
        ShipperAddress shipperAddress = shipperAddressService.queryShipperAddressById(command);

        if (shipperAddress != null) {
            // 返回寄件人地址
            Map<String, Object> data = buildReturnShipperAddressMap(shipperAddress);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_ENDER_ID_NOT_EXIST);
        }

        return SUCCESS;
    }

    private List<Map<String, Object>> buildReturnShipperAddressList(List<ShipperAddress> rsList) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;
        for (ShipperAddress shipperAddress : rsList) {
            map = buildReturnShipperAddressMap(shipperAddress);
            list.add(map);
        }
        return list;
    }

    private Map<String, Object> buildReturnShipperAddressMap(ShipperAddress shipperAddress) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("shipperAddrId", shipperAddress.getShipperAddressId());
        map.put("shipperCountryId", shipperAddress.getCountryId());
        map.put("shipperCountryCode", shipperAddress.getCountryCode());
        map.put("shipperCountry", shipperAddress.getCountryName());
        map.put("shipperStateId", shipperAddress.getRegionId());
        map.put("shipperStateCode", shipperAddress.getRegionCode());
        map.put("shipperState", shipperAddress.getRegionName());
        map.put("shipperCityId", shipperAddress.getCityId());
        map.put("shipperCity", shipperAddress.getCity());
        map.put("shipperAddr", shipperAddress.getShipperAddress());
        map.put("shipperEmail", shipperAddress.getEmail());
        map.put("shipperName", shipperAddress.getContactName());
        map.put("shipperContactNo", shipperAddress.getPhone());
        map.put("shipperZipCode", shipperAddress.getPostal());
        return map;
    }

    private ShipperAddressCommand buildShipperAddressCommand(JSONObject json) {
        ShipperAddressCommand command = new ShipperAddressCommand();
        if (json.containsKey("shipperAddrId")) {
            command.setShipperAddressId(json.getLong("shipperAddrId"));
        }

        if (json.containsKey("shipperCountryId")) {
            command.setCountryId(json.getLong("shipperCountryId"));
        }
        if (json.containsKey("shipperCountryCode")) {
            command.setCountryCode(json.getString("shipperCountryCode"));
        }
        if (json.containsKey("shipperCountry")) {
            command.setCountryName(json.getString("shipperCountry"));
        }

        if (json.containsKey("shipperStateId")) {
            command.setRegionId(json.getLong("shipperStateId"));
        }
        if (json.containsKey("shipperStateCode")) {
            command.setRegionCode(json.getString("shipperStateCode"));
        }
        if (json.containsKey("shipperState")) {
            command.setRegionName(json.getString("shipperState"));
        }

        if (json.containsKey("shipperCityId")) {
            command.setCityId(json.getLong("shipperCityId"));
        }
        if (json.containsKey("shipperCity")) {
            command.setCity(json.getString("shipperCity"));
        }

        if (json.containsKey("shipperAddr")) {
            command.setShipperAddress(json.getString("shipperAddr"));
        }

        if (json.containsKey("shipperEmail")) {
            command.setEmail(json.getString("shipperEmail"));
        }

        if (json.containsKey("shipperName")) {
            command.setContactName(json.getString("shipperName"));
        }

        if (json.containsKey("shipperContactNo")) {
            command.setPhone(json.getString("shipperContactNo"));
        }

        if (json.containsKey("shipperZipCode")) {
            command.setPostal(json.getString("shipperZipCode"));
        }

        CommandContext ctx = CommandContext.getContext();

        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        command.setOrgId(bpartner.getAdOrgId());
        command.setClientId(bpartner.getAdClientId());
        command.setUpdatedby(bpartner.getcBpartnerId());
        command.setCreatedby(bpartner.getcBpartnerId());
        command.setbPartnerId(bpartner.getcBpartnerId());
        command.setOrgId(bpartner.getAdOrgId());

        return command;
    }

    private ShipperAddressUpdateCommand buildUpdateShipperAddressCommand(JSONObject json) {
        ShipperAddressUpdateCommand command = new ShipperAddressUpdateCommand();
        if (json.containsKey("shipperAddrId")) {
            command.setShipperAddressId(json.getLong("shipperAddrId"));
        }

        // shipperCountry
        if (json.containsKey("shipperCountryId")) {
            command.setCountryId(json.getLong("shipperCountryId"));
        }
        if (json.containsKey("shipperCountryCode")) {
            command.setCountryCode(json.getString("shipperCountryCode"));
        }
        if (json.containsKey("shipperCountry")) {
            command.setCountryName(json.getString("shipperCountry"));
        }

        // shipperState
        if (json.containsKey("shipperStateId")) {
            command.setRegionId(json.getLong("shipperStateId"));
        }
        if (json.containsKey("shipperStateCode")) {
            command.setRegionCode(json.getString("shipperStateCode"));
        }
        if (json.containsKey("shipperState")) {
            command.setRegionName(json.getString("shipperState"));
        }

        // shipperCity
        if (json.containsKey("shipperCityId")) {
            command.setCityId(json.getLong("shipperCityId"));
        }
        if (json.containsKey("shipperCity")) {
            command.setCity(json.getString("shipperCity"));
        }

        if (json.containsKey("shipperAddr")) {
            command.setShipperAddress(json.getString("shipperAddr"));
        }

        if (json.containsKey("shipperEmail")) {
            command.setEmail(json.getString("shipperEmail"));
        }

        if (json.containsKey("shipperName")) {
            command.setContactName(json.getString("shipperName"));
        }

        if (json.containsKey("shipperContactNo")) {
            command.setPhone(json.getString("shipperContactNo"));
        }

        if (json.containsKey("shipperZipCode")) {
            command.setPostal(json.getString("shipperZipCode"));
        }

        CommandContext ctx = CommandContext.getContext();

        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        command.setOrgId(bpartner.getAdOrgId());
        command.setClientId(bpartner.getAdClientId());
        command.setUpdatedby(bpartner.getcBpartnerId());
        command.setCreatedby(bpartner.getcBpartnerId());
        command.setbPartnerId(bpartner.getcBpartnerId());
        command.setOrgId(bpartner.getAdOrgId());

        return command;
    }

    private ShipperAddressDeleteCommand buildDeleteShipperAddressCommand(JSONObject json) {
        ShipperAddressDeleteCommand command = new ShipperAddressDeleteCommand();
        if (json.containsKey("shipperAddrId")) {
            command.setShipperAddressId(json.getLong("shipperAddrId"));
        }

        Bpartner bpartner = (Bpartner) CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        command.setbPartnerId(bpartner.getcBpartnerId());

        return command;
    }

    private ShipperAddressQueryCommand buildQueryShipperAddressCommand(JSONObject json) {
        ShipperAddressQueryCommand command = new ShipperAddressQueryCommand();
        if (json.containsKey("shipperAddrId")) {
            command.setShipperAddressId(json.getLong("shipperAddrId"));
        }

        Bpartner bpartner = (Bpartner) CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        command.setbPartnerId(bpartner.getcBpartnerId());

        return command;
    }

    private void validCreateShipperAddress(JSONObject json) {
        // shipperCountryId
        ValidateUtil.validNotNull(json, "shipperCountryId");
        ValidateUtil.validInteger(json, "shipperCountryId");
        // shipperCountryCode
        ValidateUtil.validNotNull(json, "shipperCountryCode");
        ValidateUtil.validMaxLength(json, "shipperCountryCode", 50);
        // shipperCountry
        ValidateUtil.validNotNull(json, "shipperCountry");
        ValidateUtil.validMaxLength(json, "shipperCountry", 50);

        // shipperStateId
        ValidateUtil.validNotNull(json, "shipperStateId");
        ValidateUtil.validInteger(json, "shipperStateId");
        // shipperStateCode
        ValidateUtil.validNotNull(json, "shipperStateCode");
        ValidateUtil.validMaxLength(json, "shipperStateCode", 20);
        // shipperState
        ValidateUtil.validNotNull(json, "shipperState");
        ValidateUtil.validMaxLength(json, "shipperState", 20);

        // shipperCityId
        ValidateUtil.validNotNull(json, "shipperCityId");
        ValidateUtil.validInteger(json, "shipperCityId");
        // shipperCity
        ValidateUtil.validNotNull(json, "shipperCity");
        ValidateUtil.validMaxLength(json, "shipperCity", 50);

        // shipperAddr
        ValidateUtil.validNotNull(json, "shipperAddr");
        ValidateUtil.validMaxLength(json, "shipperAddr", 100);

        // shipperEmail
        ValidateUtil.validMaxLength(json, "shipperEmail", 60);
        if (ValidateUtil.isExistValue(json, "shipperEmail")) {
            ValidateUtil.validEmail(json, "shipperEmail");
        }

        // shipperName
        ValidateUtil.validNotNull(json, "shipperName");
        ValidateUtil.validMaxLength(json, "shipperName", 50);

        // shipperContactNo
        ValidateUtil.validNotNull(json, "shipperContactNo");
        ValidateUtil.validMaxLength(json, "shipperContactNo", 20);

        // shipperZipCode
        ValidateUtil.validNotNull(json, "shipperZipCode");
        ValidateUtil.validMaxLength(json, "shipperZipCode", 10);

    }

    private void validUpdateShipperAddress(JSONObject json) {

        boolean required = true;

        // shipperAddrId
        ValidateUtil.validNotNull(json, "shipperAddrId");
        ValidateUtil.validMaxLength(json, "shipperAddrId", 50);

        // shipperCountryId
        ValidateUtil.validInteger(json, "shipperCountryId", required);
        // shipperCountryCode
        ValidateUtil.validMaxLength(json, "shipperCountryCode", 50, required);
        // shipperCountry
        ValidateUtil.validMaxLength(json, "shipperCountry", 50, required);

        // shipperStateId
        ValidateUtil.validInteger(json, "shipperStateId", required);
        // shipperStateCode
        ValidateUtil.validMaxLength(json, "shipperStateCode", 20, required);
        // shipperState
        ValidateUtil.validMaxLength(json, "shipperState", 20, required);

        // shipperCityId
        ValidateUtil.validInteger(json, "shipperCityId", required);
        // shipperCity
        ValidateUtil.validMaxLength(json, "shipperCity", 50, required);

        // shipperAddr
        ValidateUtil.validMaxLength(json, "shipperAddr", 100, required);

        // shipperEmail
        ValidateUtil.validMaxLength(json, "shipperEmail", 60);
        if (ValidateUtil.isExistValue(json, "shipperEmail")) {
            ValidateUtil.validEmail(json, "shipperEmail");
        }

        // shipperName
        ValidateUtil.validMaxLength(json, "shipperName", 50, required);

        // shipperContactNo
        ValidateUtil.validMaxLength(json, "shipperContactNo", 20, required);

        // shipperZipCode
        ValidateUtil.validMaxLength(json, "shipperZipCode", 10, required);

    }

    private void validShipperAddressId(JSONObject json) {
        // shipperAddrId
        ValidateUtil.validNotNull(json, "shipperAddrId");
        ValidateUtil.validInteger(json, "shipperAddrId");
    }

}
